import re
import os
from datetime import datetime
from collections import defaultdict

# 常量定义
EXCLUDED_SERVICES = {'1001'}  # 需要排除的服务列表


def parse_log_file(filename, service_data):
    with open(filename, 'r', encoding='utf-8') as f:
        log_content = f.read()

    time_pattern = r'INFO \|(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}),\d{3} \+0800\|'
    blocks = re.split(time_pattern, log_content)
    valid_blocks = [(blocks[i], blocks[i + 1]) for i in range(1, len(blocks) - 1, 2)]
    proto_list = []
    if not valid_blocks:
        return

    latest_time = None
    latest_content = ""
    for time_str, content in valid_blocks:
        try:
            current_time = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
            if not latest_time or current_time > latest_time:
                latest_time = current_time
                latest_content = content
        except ValueError:
            continue

    file_data = {}
    lines = latest_content.split('\n')
    for line in lines:
        if re.match(r'^\s*\d+', line):
            parts = [p.strip() for p in line.split('|') if p.strip()]
            if len(parts) >= 10:
                name = parts[0]
                proto_list.append(name)
                file_data[name] = {
                    'tpm': int(parts[2]),
                    'success': float(parts[3].replace('%', '')),
                    'max_time': int(parts[5]),
                    'avg_time': int(parts[6]),
                    'avg90_time': int(parts[7])
                }
    service_data[filename] = file_data
    print("count service_data::",service_data)
    return proto_list

def safe_avg(data_list):
    return sum(data_list) / len(data_list) if data_list else 0
def safe_max(data_list):
    return max(data_list) if data_list else 0

def calculate_stats(services):
    stats = {
        'tpm_list': [],
        'success_list': [],
        'max_times': [],
        'avg_times': [],
        'avg90_times': []
    }

    for name, srv in services.items():
        # 所有服务参与TPM和响应时间统计
        stats['tpm_list'].append(srv['tpm'])
        stats['max_times'].append(srv['max_time'])
        stats['avg_times'].append(srv['avg_time'])
        stats['avg90_times'].append(srv['avg90_time'])

        # 仅成功率排除指定服务
        if name not in EXCLUDED_SERVICES:
            stats['success_list'].append(srv['success'])

    return {
        'avg_tpm': safe_avg(stats['tpm_list']),
        'avg_success': safe_avg(stats['success_list']),
        'avg_max_time': safe_max(stats['max_times']),
        'avg_response': safe_avg(stats['avg_times']),
        'avg_90th': safe_avg(stats['avg90_times'])
    }


def main():
    service_data = defaultdict(dict)

    log_files = [f for f in os.listdir('.') if f.startswith('elapse')]
    for filename in log_files:
        try:
            proto_list = parse_log_file(filename, service_data)
            print(f"协议列表: {proto_list}")
        except Exception as e:
            print(f"处理错误 {filename}: {str(e)}")
    print(199,service_data)
    # 文件级统计
    for filename, data in service_data.items():
        print(f"\n▶️ 文件 [{filename}] 最新数据")
        print("─" * 85)
        print("{:<8} | {:<6} | {:<8} | {:<8} | {:<8} | {:<8}".format(
            "服务", "TPM", "成功率", "最大响应", "平均响应", "90%响应"))
        for name, metrics in data.items():
            print(f"{name.ljust(8)} | {metrics['tpm']:6} | {metrics['success']:7.2f}% | "
                  f"{metrics['max_time']:8}ms | {metrics['avg_time']:8}ms | {metrics['avg90_time']:8}ms")

        stats = calculate_stats(data)
        print(f"\n📊 文件统计（已排除服务 {EXCLUDED_SERVICES} 的成功率）:")
        print(f"平均 TPM: {stats['avg_tpm']:.2f}")
        print(f"平均成功率: {stats['avg_success']:.2f}%")
        print(f"最大响应时间: {stats['avg_max_time']:.2f}ms")
        print(f"平均响应时间: {stats['avg_response']:.2f}ms")
        print(f"90%响应耗时: {stats['avg_90th']:.2f}ms")
        print("─" * 85)

    # 全局统计
    all_tpms, all_success = [], []
    all_max, all_avg, all_90th = [], [], []

    for filename_data in service_data.values():
        for name, data in filename_data.items():
            all_tpms.append(data['tpm'])
            all_max.append(data['max_time'])
            all_avg.append(data['avg_time'])
            all_90th.append(data['avg90_time'])
            if name not in EXCLUDED_SERVICES:
                all_success.append(data['success'])

    print(f"\n🔍 全局统计（已排除服务 {EXCLUDED_SERVICES} 的成功率）:")
    print("=" * 85)
    print(f"总服务数量: {len(all_tpms)}")
    print(f"平均 TPM: {safe_avg(all_tpms):.2f}")
    print(f"平均成功率: {safe_avg(all_success):.2f}%")
    print(f"最大响应时间: {safe_avg(all_max):.2f}ms")
    print(f"平均响应时间: {safe_avg(all_avg):.2f}ms")
    print(f"90%响应耗时: {safe_avg(all_90th):.2f}ms")
    print("=" * 85)


if __name__ == "__main__":
    main()